package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private TimeLineService timeLineService;

    /**
     * 发布动态
     */
    public String save(Movement movement) {
        //打印线程名称
        String name = Thread.currentThread().getName();
        System.out.println("主线程："+name);
        //1、保存动态详情到数据库表中
        mongoTemplate.save(movement);
        //2、调用TimeLineService异步保存关系表数据
        timeLineService.saveTimeLine(movement);
        return movement.getId().toString();
    }

    //根据用户id，查询此用户发布的动态列表
    public List<Movement> findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1); //查询审核通过
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Movement.class);
    }

    //根据好友id，查询此用户好友发布的动态列表
    public List<Movement> findByFriendId(Long friendId, Integer page, Integer pagesize) {
        //i：根据friendId查询（动态-好友关系表） List<MovementTimeLine>
        Criteria lineCrieria = Criteria.where("friendId").is(friendId);
        Query lineQuery = Query.query(lineCrieria)
                        .with(Sort.by(Sort.Order.desc("created")))
                        .skip((page-1) * pagesize)
                        .limit(pagesize);
        List<MovementTimeLine> lines = mongoTemplate.find(lineQuery, MovementTimeLine.class);
        //ii: 提取所有的动态id
        //从list集合中提取对象的某个属性 (集合，需要提取的属性名，类型.class)
        List<ObjectId> ids = CollUtil.getFieldValues(lines, "movementId", ObjectId.class);
        //iii：查询动态表，根据动态id查询所有的动态数据对象
        Criteria criteria = Criteria.where("id").in(ids).and("state").is(1);
        Query query = Query.query(criteria);
        return mongoTemplate.find(query,Movement.class);
    }

    //根据动态的id列表，查询动态数据
    public List<Movement> findByIds(String[] movementIds, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("id").in(movementIds).and("state").is(1);
        Query query = Query.query(criteria)
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Movement.class);
    }

    //随机查询动态数据 (非重点)
    public List<Movement> randomMovement(Integer count) {
        //设置采样数量
        TypedAggregation<Movement> aggregation =
                TypedAggregation.newAggregation(Movement.class, Aggregation.sample(count));//采样数量
        //查询
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //从采样结果中，获取真实的数据
        return results.getMappedResults();
    }

    @Override
    public Movement findById(String id) {
        return mongoTemplate.findById(id,Movement.class);
    }

    //更新动态状态
    @Override
    public void updateState(String movementId, Integer state) {
        //构建query
        Query query = Query.query(Criteria.where("id").is(new ObjectId(movementId)));
        //构建update
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }

    //根据用户id和状态，查询动态
    public PageResult findMovements(Long userId, Integer state, Integer page, Integer pagesize) {
        //1、创建Query对象
        Query query = new Query();
        if(userId!=null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        if(state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        //2、查询总数
        long count = mongoTemplate.count(query, Movement.class);
        //3、设置分页参数
        query.with(Sort.by(Sort.Order.desc("created"))).skip((page-1)*pagesize).limit(pagesize);
        //4、查询列表
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        //5、返回
        return new PageResult(page,pagesize,count,list);
    }
}
